package cn.nawang.ebeim.ui.util;

import java.io.File;
import java.util.Comparator;
import java.util.regex.Pattern;

public class StringComparator implements Comparator<File>{  
    @Override  
    public int compare(File f1, File f2) {  
        Pattern pattern = Pattern.compile(".*\\d+.*");
        String s1 = f1.getName().toLowerCase(),s2 = f2.getName().toLowerCase();
        if(pattern.matcher(s1).matches()&&pattern.matcher(s2).matches()){
          return sort(s1, s2,0);
       }
       return s1.compareTo(s2);
    }  
    
    public int sort(String s1, String s2,int tryCount) {  
        if(tryCount==10){
            return 0;
        }
        double a = strcmp(s1,tryCount);
        if(a==0.0)return 0;
        double b = strcmp(s2,tryCount);
        if(b==0.0)return 0;
        if(a<b)  
            return -1;  
        else if(a>b)  
            return 1;  
        else  
            return sort(s1, s2,++tryCount);  
          
    }  
      
    public double strcmp(String str,int tryCount){  
        int count = 0;
        StringBuffer sb = new StringBuffer();  
        for(int i=0;i<str.length();i++){  
            if(Character.isDigit(str.charAt(i)))  
                sb.append(str.charAt(i));  
            else if(str.charAt(i)=='.'&&i<str.length()-1&&Character.isDigit(str.charAt(i+1)))  
                sb.append(str.charAt(i));
            else if(sb.length()>0 && count >= tryCount){
                break;
            }else if(count >= tryCount){
               return (int)str.charAt(i);
            }else{
                count++;
            } 
                
        }  
        if(sb.toString().isEmpty())  
            return 0;  
        else  
            return Double.parseDouble(sb.toString());  
    }
    
}